package cn.nawang.ebeim.server.task;

import cn.nawang.ebeim.server.service.StorageServiceFactory;
import cn.nawang.ebeim.server.util.PathBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

public class UploadFileTask implements Task {

    private static final Logger LOG = LoggerFactory.getLogger(UploadFileTask.class);

    private String fileAbsPath;

    public UploadFileTask(String filePath) {
        this.fileAbsPath = filePath;
    }

    public void execute() {
        File uploadFile = new File(fileAbsPath);
        String signature = uploadFile.getName();
        String dataSourceId = uploadFile.getParentFile().getName();
        StorageServiceFactory.getStorageService().uploadFile(dataSourceId, signature, fileAbsPath);
        String downloadPath = PathBuilder.builderFileDownloadPath(dataSourceId, signature);
        moveToDownloadCache(uploadFile, downloadPath);
        LOG.info("execute uploadFileTask success:{}", uploadFile);
    }

    private void moveToDownloadCache(File uploadFile, String downloadPath) {
        File finalFile = new File(downloadPath);
        if (!finalFile.getParentFile().exists()) {
            finalFile.getParentFile().mkdirs();
        }
        boolean rename = uploadFile.renameTo(finalFile);
        if (!rename) {
            boolean delete = uploadFile.delete();
            LOG.error(uploadFile + ": 移动至缓存文件夹失败,直接删除! " + delete);
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        UploadFileTask that = (UploadFileTask) o;
        if (fileAbsPath != null ? !fileAbsPath.equals(that.fileAbsPath) : that.fileAbsPath != null) return false;
        return true;
    }

    @Override
    public int hashCode() {
        return fileAbsPath != null ? fileAbsPath.hashCode() : 0;
    }

    @Override
    public String toString() {
        return fileAbsPath;
    }

}
